/*本模块功能:课程管理_自定义课程库(管理员)
        编写者:朱光曜
        编写时间:2017.11.15*/
$(function() {
    var string1 = '<tr>' +
        '<th class="col-lg-2"><input type="checkbox" name="controlAll" id="controlAll" class="allCheck"></th>' +
        '<th class="col-lg-7">专业</th>' +
        '<th class="col-lg-9">专业方向</th>' +
        '<th class="col-lg-7">课程名称</th>' +
        '<th class="col-lg-7">制作教师</th>' +
        '<th class="col-lg-4">学分</th>' +
        '<th class="col-lg-5">操作</th>' +
        '</tr>';
    var confirm1 = new Confirm;
    var confirm2 = new Confirm;
    var Alert1 = new Alert;
    var Alert2 = new Alert;



    function locationInformationd(data) { //搜索
        var selectDepartment = ""; //院系
        for(key in data.departmentList) {
            selectDepartment += '<option value="1" class="optionList" departmentId="' + data.departmentList[key].departmentId + '">' + data.departmentList[key].departmentName + '</option>';
        }


        return '<div class="fl inputRight"><label for="selectDepartment">院&ensp;&ensp;&ensp;&ensp;系:&ensp;</label>' +
            '<select id="selectDepartment" class="publicSelect" >' +
            '<option value="1">请选择</option>' +
            selectDepartment +
            '</select>' +
            '</div>' +
            '<div class="fl inputRight"><label for="selectMajor">专&ensp;&ensp;&ensp;&ensp;业:&ensp;</label>' +
            '<select id="selectMajor" class="publicSelect">' +
            '<option value="1">请选择</option>' +

            '</select>' +
            '</div>' +
            '<div class="fl inputRight"><label for="curriculum">制作教师:&ensp;</label><input autocomplete="off" type="text" id="curriculum" class="publicText" placeholder="请输入教师姓名" /></div>' +
            '<div class="fl publicBtn searchBtn">搜索</div>' +

            '<div class="fr publicBtn deleteCurriculum">删除课程</div>';
    }

    function tabelModel(data) { //列表

        return '<tr data-num="0"  courseId="' + data.courseList[key].courseId + '" >' +
            '<td class="col-lg-2"><input autocomplete="off" value="0" name="selecteds" type="checkbox" class="oneCheck" courseId="' + data.courseList[key].courseId + '" /></td>' +
            '<td class="col-lg-10"  title='+ data.courseList[key].professionName +'>' + data.courseList[key].professionName + '</td>' +
            '<td class="col-lg-10"  title='+ data.courseList[key].directName +'>' + data.courseList[key].directName + '</td>' +
            '<td class="col-lg-10"  title='+ data.courseList[key].courseName +'>' + data.courseList[key].courseName + '</td>' +
            '<td class="col-lg-10"  title='+ data.courseList[key].userName +'>' + data.courseList[key].userName + '</td>' +
            '<td class="col-lg-10"  title='+ data.courseList[key].courseCredit +'>' + data.courseList[key].courseCredit + '</td>' +

            '<td class="col-lg-4">' +
            // '<a href="javascript:;" class="download">下载<div class="bubble"> <span></span> <em></em><p num="1" class="num1 have">学习课件</p><p num="2" class="num2 have">实验手册</p><p num="3" class="num3  have">备课材料</p><p num="4" class="num4 have">课后作业 </p><p num="5" class="num5 have">学习视频</p><p num="6" class="num6 have">课程材料</p></div></a>'+
            '<a href="javascript:;" class="download">下载<div class="bubble"> <span></span> <em></em><p num="1" class="num1 have">学习课件</p><p num="4" class="num4 have">课后作业 </p><p num="5" class="num5 have">学习视频</p><p num="6" class="num6 have">课程材料</p></div></a>'+
            '<a href="javascript:;" class="details">详情</a>'+
            '</td>' +
            '</tr>';

    }
    var loading1 = new Loading();//监控全局ajax添加loading
    loading1.init();
    $(document).ajaxSend(function(){
        loading1.show();

    });
    $(document).ajaxStop(function(){
        loading1.hide();

    });
    document.addEventListener('DOMSubtreeModified',function(e){//去除空格
        $(".publicText").attr("maxlength","20");


        $.map($(".publicText"),function (opt) {//长度限制
            maxLengthLimit.init(opt);
        });
        $(".publicText").bind('input propertychange',function(){

            var regy = /\s/g;
            if(regy.test($(this).val())){
                $(this).val($(this).val().replace(/\s|\xA0/g,"")) ;
            }
        });
    });
    var nowData = 1;
    var index = {
        init: function() {
            this.bind();
        },
        bind: function() {
            var self = this;
            this.data_content = {}; //搜索集
            this.tab_content = {}; //列表集
            this.parameter = {
                "pageNow": 1,
                "pageSize": 10,
                "saveMark":0
            };

            this.postData(this.parameter, nowData);

        },
        postData: function(par_data, nowData,hunt) { //获得搜索及列表数据
            var self = this;
            var parameter = par_data;

            $.ajax({
                type: "post",
                url: "skipCourseList",
                async: true,
                data: {
                    "jsonStr": JSON.stringify(parameter)
                },
                success: function(data, status, xhr) {
                    var new_data = JSON.parse(data);
                    if(new_data.result == "success"){
                        if(hunt) {
                            self.tab_content = new_data;

                            self.tab_add();
                        } else {

                            self.data_content = new_data;
                            self.tab_content = new_data;

                            self.add();
                            self.tab_add();
                        }
                        // console.log(new_data.totalPage+"啊啊"+new_data.pageNow)
                        var sumpage = new_data.totalPage;
                        if(sumpage<1){sumpage=1;};
                        var nowpage = 1;
                        var pagenumber = 10;
                        var parame = parameter;
                        $(".tcdPageCode").createPage({
                            pageCount: sumpage, //总页数
                            current: nowpage, //当前页数
                            pageNumber: pagenumber, //每页显示数量
                            backFn: function(p) {

                                nowpage = p;

                                if(nowpage >= sumpage) {
                                    nowpage = sumpage;
                                }
                                if(!parameter) {
                                    parameter = {
                                        "pageNow": nowpage,
                                        "pageSize": 10,
                                        "saveMark":0
                                    };

                                } else {
                                    parameter.pageNow = nowpage;

                                }
                                $.ajax({
                                    type: "post",
                                    url: "skipCourseList",
                                    async: true,
                                    data: {
                                        "jsonStr": JSON.stringify(parameter)
                                    },
                                    async: true,
                                    success: function(msg) {
                                        //获取课程
                                        var msgNew = JSON.parse(msg);
                                        self.tab_content = msgNew;

                                        self.tab_add();
                                    },
                                    error: function(data, status, xhr) {
                                        var json = JSON.stringify({
                                            "pageName": "error"
                                        });
                                        window.location.href = "skipPage?jsonStr=" + json;

                                    }
                                });
                            }
                        });
                    }else{
                        if(new_data.failMsg == "暂无权限"){
                            parent.location.reload(true);
                        }
                    }

                },
                error: function(data, status, xhr) {
                    var json = JSON.stringify({
                        "pageName": "error"
                    });
                    window.location.href = "skipPage?jsonStr=" + json;

                }
            });
        },
        add: function() { //搜索追加
            var self = this;
            var data = self.data_content;

            $("#searchCriteria").html(locationInformationd(data));

            $("#selectDepartment").on("change", function() {//院系联动专业
                if($("#selectDepartment option:selected").attr("departmentid") == null) {

                    $("#selectMajor").html('<option value="1" >请选择</option>');
                } else {

                    var parameter = {
                        "departmentId": $("#selectDepartment option:selected").attr("departmentid")
                    };

                    $.ajax({
                        type: "post",
                        url: "getProfessionListByDepmentId",
                        async: true,
                        data: {
                            "jsonStr": JSON.stringify(parameter)
                        },
                        success: function(data) {
                            //获取地点

                            var msgNew = JSON.parse(data);
                            var con = "";

                            for(key in msgNew.professionList) {
                                con += '<option value="1" professionId="' + msgNew.professionList[key].professionId + '">' + msgNew.professionList[key].professionName + '</option>';
                            }
                            $("#selectMajor").html(con);

                        },
                        error: function(data, status, xhr) {
                            var json = JSON.stringify({
                                "pageName": "error"
                            });
                            window.location.href = "skipPage?jsonStr=" + json;

                        }
                    });
                }
            });
            $(".funBox .searchBtn").off("click").click(function() { //搜索点击

                var userName = $("#curriculum").val();
                var departmentId = $("#selectDepartment option:selected").attr("departmentId");
                var professionId = $("#selectMajor option:selected").attr("professionid");
                var nowData = 1;
                if(verification.specialCode(userName)!==true){
                    self.alert1("不能输入特殊字符(@/'\"#$%&^*)");
                    return;
                }
                var parameter = {
                    "saveMark":0,
                    "pageNow": 1,
                    "pageSize": 10
                };
                if(userName!=''){
                    parameter.userName = userName;
                }
                if(departmentId!=undefined){
                    parameter.departmentId = departmentId;
                }
                if(departmentId!=undefined){
                    parameter.professionId = professionId;
                }
                // var j=0;
                // //遍历删除空元素
                // for(i in parameter){
                // 	if(j==0){j++;continue;}
                // 	if(parameter[i]==null||parameter[i]==""){
                // 		delete parameter[i];
                // 	}
                // 	if(!isNaN(parameter[i])){
                // 		parameter[i]=Number(parameter[i]);
                // 	}
                // }


                self.postData(parameter, nowData,1);
            });
            $(".deleteCurriculum").off("click").on("click", function() { //删除课程
                self.delListEvent();
            });

        },
        tab_add: function() { //列表追加

            var self = this;
            var data = self.tab_content;
            var table = string1;

            //data.selectList={};

            var i = 0;
            for(key in data.courseList) {
                i++;
            }

            if(i > 0) {

                for(key in data.courseList) {

                    table += tabelModel(data);
                }

                $(".mainContent .tableBox").html(table);
            } else {
                var trImg = "<tr><td colspan='7'><img style='margin: 80px auto 20px;' src='pc/images/ico_noneData.png'><p style='font-size:26px;color:#8a8a8a;width:100%;text-align:center;'>暂无数据</p></td/tr>";
                $(".mainContent .tableBox").html(string1 + trImg);
            }
            //设置列表宽度(最大为9)
            var numMax = 0;
            $(".tableBox tr th").each(function() {
                var str = $(this).attr("class");
                var num = str.lastIndexOf("col-lg-") + 7;
                var num1 = parseFloat(str.substring(num, num + 1));
                numMax += num1;
            });

            $(".tableBox tr th").each(function() {
                var str = $(this).attr("class");
                var num = str.lastIndexOf("col-lg-") + 7;
                var num1 = parseFloat(str.substring(num, num + 1));

                $(this).css("width",num1 / numMax * 100+ "%");
            });


            self.allCheckEvent();
            $(".details").off("click").on("click",function(){//详情跳页
                var json=JSON.stringify({
                    "pageName":"adminMyCourse",
                    "paramData":{
                        "courseId":parseInt($(this).parents("tr").attr("courseId")),
                        "pageName":"adminCourseLibraryCustomization"
                    }

                });

                window.location.href="skipPage?jsonStr="+json;
            });


            $(".download").off("click").on("click",function(event) { //下载


                $(".bubble").hide();
                $(this).children(".bubble").show();
                var courseId=$(this).parents("tr").children("td").eq(0).children("input").attr("courseId");
                var getDownloadMarkParameters={
                    "courseId":courseId
                };
                var myClick=$(this);

                $.ajax({
                    type: "post",
                    url: "getDownloadMark",
                    async: true,
                    data: {
                        "jsonStr": JSON.stringify(getDownloadMarkParameters)
                    },

                    success: function(msg) {
                        var courseIds=courseId;
                        var msgNew = JSON.parse(msg);

                        if(msgNew.result == "success") {
                            for(key in msgNew.cantDownList){

                                myClick.children(".bubble").children(".num"+msgNew.cantDownList[key]).removeClass("have").css({"color":"#999","cursor":"not-allowed"});

                            }
                            $(".download .bubble p").off("click").click(function(event){
                                event.stopPropagation();
                            });
                            $(".download .bubble .have").off('click').click(function(){

                                var downloadCourseFileParameters={
                                    "courseId":parseInt(courseIds),
                                    "downloadType":parseInt($(this).attr("num"))
                                };

                                //window.location.href="downloadCourseFile?jsonStr="+JSON.stringify(downloadCourseFileParameters);
                                $.ajax({
                                    type: "post",
                                    url: "downloadCourseFile",
                                    async: true,
                                    data: {
                                        "jsonStr": JSON.stringify(downloadCourseFileParameters)
                                    },

                                    success: function(msg) {

                                        var msgNew = JSON.parse(msg);

                                        if(msgNew.result == "success") {
                                            window.location.href=msgNew.url;
                                        } else {
                                            //self.alert1(msgNew.failMsg);
                                            if(msgNew.failMsg){
                                                self.alert1(msgNew.failMsg);
                                            }else{
                                                self.alert1("下载失败");
                                            }

                                        }

                                    },
                                    error: function(data, status, xhr) {
                                        var json = JSON.stringify({
                                            "pageName": "error"
                                        });
                                        window.location.href = "skipPage?jsonStr=" + json;

                                    }
                                });
                                return false;
                            });



                        } else {
                            //self.alert1("加载失败");
                            if(msgNew.failMsg){
                                self.alert1(msgNew.failMsg);
                            }else{
                                self.alert1("加载失败");
                            }

                        }

                    },
                    error: function(data, status, xhr) {
                        var json = JSON.stringify({
                            "pageName": "error"
                        });
                        window.location.href = "skipPage?jsonStr=" + json;

                    }

                });
                event.stopPropagation();

            });
            $(document).on("click",function(event) {

                $(".bubble").hide();

            });

        }/*,
		submits: function(saveRelationPageParameters) { //弹窗提交
			console.log(saveRelationPageParameters)
			var self = this;
			$.ajax({
				type: "post",
				url: "saveRelationPage",
				async: true,
				data: {
					"jsonStr": JSON.stringify(saveRelationPageParameters)
				},

				success: function(msg) {

					var msgNew = JSON.parse(msg);

					if(msgNew.result == "success") {
						self.alert1("提交成功");
					} else {
						self.alert1("提交失败");
					}

				},
				error: function(data, status, xhr) {
					var json = JSON.stringify({
						"pageName": "error"
				    });
					window.location.href = "skipPage?jsonStr=" + json;

				}
			});
		}*/,
        alert1: function(content1,state) { //confirm提示

            Alert1.contenthead = "提示";
            Alert1.content = content1;

            Alert1.success = function() {
                if(state=="success"){
                    window.location.reload();
                }
                //
                $(".bubble").hide();
                Alert1.hide();
            };

            Alert1.init();
            Alert1.show();
        },
        allCheckEvent: function() {
            //全选
            allCheck.init("controlAll", "oneCheck");
        },
        delListEvent: function() { //批量删除
            var $_self = this;
            if($(".oneCheck[value=1]").length == 0) {
                Alert1.contenthead = "提示";
                Alert1.content = "请选择要删除的课程";
                Alert1.success = function() {};
                Alert1.init();
                Alert1.show();
            } else {

                confirm1.success = function() {
                    var list = [];
                    $(".box_1 tr td .oneCheck").each(function() {
                        if(parseInt($(this).val()) == 1) {
                            list.push($(this).attr("courseId"));

                        }

                    });
                    var self = $_self;
                    var del=function(){
                        var deleteCurriculumparameters = list;

                        $.ajax({
                            type: "post",
                            url: "delCourse",
                            async: true,
                            data: {
                                "jsonStr": JSON.stringify(deleteCurriculumparameters)
                            },

                            success: function(msg) {

                                var msgNew = JSON.parse(msg);

                                if(msgNew.result == "success") {
                                    self.alert1("删除成功","success");
                                } else {
                                    if(msgNew.failMsg){
                                        self.alert1(msgNew.failMsg);
                                    }else{
                                        self.alert1("删除失败");
                                    }
                                }

                            },
                            error: function(data, status, xhr) {
                                var json = JSON.stringify({
                                    "pageName": "error"
                                });
                                window.location.href = "skipPage?jsonStr=" + json;

                            }
                        });
                    };
                    var isVmparameters =list;
                    $.ajax({//判断是否存在虚拟机
                        type: "post",
                        url: "getDelCourseMark",
                        async: true,
                        data: {
                            "jsonStr": JSON.stringify(isVmparameters),
                            "memType":1
                        },

                        success: function(msg) {

                            var msgNew = JSON.parse(msg);

                            if(msgNew.result == "success") {
                                if(msgNew.result.relationMark==0){
                                    del();
                                }else{
                                    self.confirm2("当前所选择的课程含有排课信息，确定要删除吗？",del);
                                }

                            } else {
                                //self.alert1("删除失败");
                                if(msgNew.failMsg){
                                    self.alert1(msgNew.failMsg);
                                }else{
                                    self.alert1("删除失败");
                                }

                            }

                        },
                        error: function(data, status, xhr) {
                            var json = JSON.stringify({
                                "pageName": "error"
                            });
                            window.location.href = "skipPage?jsonStr=" + json;

                        }
                    });
                };
                var num = 0;
                $(".box_1 tr td .oneCheck").each(function() {
                    if(parseInt($(this).val()) == 1) {
                        num++;
                    }

                });
                if(num < 2) {
                    confirm1.content = "确定删除这门课程吗";
                } else {
                    confirm1.content = "确定删除这<a href='javascript:void(0)'>" + num + "</a>门课程吗";
                }

                confirm1.init();
                $(".alert_content a").css({
                    "margin": "2px",
                    "color": "#c82011",
                    "text-decoration": "underline"
                });
                confirm1.show();

            }
        },
        confirm2: function(content1,method) { //confirm提示

            confirm2.contenthead = "提示";
            confirm2.content = content1;

            confirm2.success = method;

            confirm2.init();
            confirm2.show();
        }

    };
    index.init();

});